package db

import (
	"errors"
	"litetalk/proto"

	"github.com/jinzhu/gorm"
)

type IMGroupMember struct {
	gorm.Model
	GroupId uint `gorm:"primaryKey;autoIncrement:false"`
	UserId  uint `gorm:"primaryKey;autoIncrement:false"`
	Status  int
}

var GroupMember IMGroupMember

func (i *IMGroupMember) Add() error {
	if i.GroupId == 0 || i.UserId == 0 {
		return errors.New("groupId or userId is zero")
	}

	data := &IMGroupMember{}
	dbIns.Where("group_id=? and user_id=?", i.GroupId, i.UserId).First(data)
	// 已存在
	if data.ID > 0 && data.Status == proto.CID_OK {
		return nil
	}
	// 不存在
	if data.ID == 0 {
		i.Status = proto.CID_OK
		err := dbIns.Create(i).Error
		if err != nil {
			return err
		}
	} else {
		dbIns.Model(data).Update("status", proto.CID_OK)
	}
	return nil
}

func (i *IMGroupMember) Del() error {
	if i.GroupId == 0 || i.UserId == 0 {
		return errors.New("groupId or userId is zero")
	}
	data := &IMGroupMember{}
	dbIns.Where("group_id=? and user_id=?", i.GroupId, i.UserId).First(data)
	if data.ID == 0 {
		return nil
	}
	if data.ID > 0 && data.Status == proto.CID_DEL {
		return nil
	}

	dbIns.Model(data).Update("status", proto.CID_DEL)
	return nil
}

func (i *IMGroupMember) GetDataByUserId(id uint) (ret []IMGroupMember) {
	dbIns.Model(&IMGroupMember{}).Where("user_id=? and status=?", id, proto.CID_OK).Find(&ret)
	return
}

func (i *IMGroupMember) GetDataByGroupId(id uint) (ret []IMGroupMember) {
	dbIns.Model(&IMGroupMember{}).Where("group_id=? and status=?", id, proto.CID_OK).Find(&ret)
	return
}
